package com.smartstate.IOC.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.smartstate.IOC.dto.PageDTO;
import com.smartstate.IOC.entity.Alarm;
import com.smartstate.IOC.mapper.AlarmMapper;
import com.smartstate.IOC.mapper.CarbonConfigMapper;
import com.smartstate.IOC.service.AlarmService;
import com.smartstate.IOC.util.StringDateUtills;
import com.smartstate.IOC.vo.AlarmVo;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

@Transactional
@Service("alarmService")
@Slf4j
public class AlarmServiceImpl extends ServiceImpl<AlarmMapper, Alarm> implements AlarmService {

    @Autowired
    AlarmMapper alarmMapper;

    @Override
    public Page<Alarm> queryAllPageByDTO(PageDTO pageDTO) {
        return null;
    }

    @Override
    public List<Alarm> getLastTime() {
        String now = DateUtil.now();
        Date nowDate = DateUtil.parse(now);
        Date lastDate = DateUtil.offsetDay(nowDate, -3);
        List<Alarm> lastTime = alarmMapper.getLastTime(nowDate, lastDate);
        return lastTime;
    }

    @Async("genericExecutor")
    @Override
    public Future<Map<String, Object>> getAlarmCountByType(String stateType) {
        if (stateType == null) {
            stateType = "";
        }
        Map<String, Object> result = new HashMap<>();
        String itemName = "";
        //1是已处理 2是未处理 3是处理中
        switch (stateType) {
            case "1":
                itemName = "已处理";
                break;
            case "2":
                itemName = "未处理";
                break;
            case "3":
                itemName = "处理中";
                break;
            default:
                itemName = "告警事件总数";
        }
        result.put("itemName", itemName);
        result.put("itemValue", baseMapper.getAlarmCountByType(stateType));
        Future<Map<String, Object>> future = new AsyncResult<Map<String, Object>>(result);
        return future;
    }


    /**
     * 环境告警事件展示
     *
     * @param
     * @return
     */
    @Override
    public List<AlarmVo> queryPageList() {
        List<Alarm> alarms = alarmMapper.queryPageByCondition();
        ArrayList<AlarmVo> alarmVos = new ArrayList<>();
        for (Alarm alarm : alarms) {
            AlarmVo alarmVo = new AlarmVo();
            alarmVo.setAttributes(alarm.getAttributes());
            alarmVo.setRemark(alarm.getRemark());
            alarmVo.setAbnormaltime(alarm.getAbnormaltime());
            if (alarm.getState().equals("2")) {
                alarmVo.setStatu("未处理");
            } else if (alarm.getState().equals("3")) {
                alarmVo.setStatu("处理中");
            }
            alarmVos.add(alarmVo);
        }
        return alarmVos;
    }


//    /**
//     * 环境监控设备id集
//     */
//    static final List<String> ENVIRONMENT_EQUIPMENT_SET = Lists.newArrayList("1");
//    /**
//     * 视频监控设备id集
//     */
//    static final List<String> MONITOR_EQUIPMENT_SET = Lists.newArrayList("18");
//    /**
//     * 工业自控设备id集
//     */
//    static final List<String> CONTROL_EQUIPMENT_SET = Lists.newArrayList("6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17");
//    /**
//     * 电表设备id集
//     */
//    static final List<String> ELECTRICITY_METER_SET = Lists.newArrayList("2");

    @Override
    public Map<String, Integer> getAlarmTotal() {
        // 环境监控设备
        Integer integer = alarmMapper.selectAlarmEvent();
        if (integer == null) {
            integer = 0;
        }
        //视频监控设备
        Integer integer1 = alarmMapper.selectAlarmVideo();
        if (integer1 == null) {
            integer1 = 0;
        }
        //工业自控设备
        Integer integer2 = alarmMapper.selectAlarmIndustry();
        if (integer2 == null) {
            integer2 = 0;
        }
        //电表设备
        Integer integer3 = alarmMapper.selectAlarmMeter();
        if (integer3 == null) {
            integer3 = 0;
        }
        HashMap<String, Integer> maps = new HashMap<>();
        maps.put("环境监控设备", integer);
        maps.put("视频监控设备", integer1);
        maps.put("工业自控设备", integer2);
        maps.put("电表设备", integer3);
        return maps;
    }

    @Override
    public Map<String, Integer> getEnvironTotal() {
        HashMap<String, Integer> maps = new HashMap<>();
        maps.put("静压传感器", alarmMapper.getStaticPressure());
        maps.put("湿度传感器", alarmMapper.getHumidity());
        maps.put("温度传感器", alarmMapper.getTemperature());
        maps.put("露点传感器", alarmMapper.getDewPoint());
        maps.put("尘埃粒子0.5", alarmMapper.getLittleParticle());
        maps.put("尘埃粒子5.0", alarmMapper.getLongParticle());
        return maps;
    }


    @Override
    public Map<String, Long> getThreeAlarm() {
        List<String> lastMonth = getLastMonth();
        List<Alarm> threeAlarm = alarmMapper.getThreeAlarm(lastMonth.get(0), lastMonth.get(1));
        for (Alarm alarm : threeAlarm) {
            String abnormaltime = alarm.getAbnormaltime();
            alarm.setAbnormaltime(abnormaltime.substring(0, 7));
        }
        Map<String, Long> categoryCounts = threeAlarm.stream().collect(Collectors.groupingBy(Alarm::getAbnormaltime, Collectors.counting()));
        return categoryCounts;
    }


    /**
     * 获取当前时间前三个月时间
     *
     * @return
     */
    public static List<String> getLastMonth() {
        Date dNow = new Date();   //当前时间
        Date dBefore = new Date();
        Calendar calendar = Calendar.getInstance(); //得到日历
        calendar.setTime(dNow);//把当前时间赋给日历
        calendar.add(Calendar.MONTH, -3);  //设置为前3月
        dBefore = calendar.getTime();   //得到前3月的时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //设置时间格式
        String defaultStartDate = sdf.format(dBefore);    //格式化前3月的时间
        String defaultEndDate = sdf.format(dNow); //格式化当前时间
        ArrayList<String> strings = new ArrayList<>();
        strings.add(defaultStartDate);
        strings.add(defaultEndDate);
        return strings;
    }


    @Resource
    RedisTemplate redisTemplate;
    @Resource
    CarbonConfigMapper carbonConfigMapper;

    @Override
    public Map<String, Object> getEnvironAlarm() {
        //当前ioc工业看板的设备id
        String deviceId = carbonConfigMapper.getDeviceId();
        //根据设备id去redis中查询设备参数
        Map entries = redisTemplate.opsForHash().entries(deviceId);
        // 各个环境值
        HashMap<String, Object> stringIntegerHashMap = new HashMap<>();
        if (entries.get("staticPressure") != null) {
            stringIntegerHashMap.put("静压", entries.get("staticPressure"));
        } else {
            stringIntegerHashMap.put("静压", "0.0");
        }

        if (entries.get("humidity") != null) {
            stringIntegerHashMap.put("湿度", entries.get("humidity"));
        } else {
            stringIntegerHashMap.put("湿度", "0.0");
        }
        if (entries.get("temperature") != null) {
            stringIntegerHashMap.put("温度", entries.get("temperature"));
        } else {
            stringIntegerHashMap.put("温度", "0.0");

        }
        if (entries.get("dewPoint") != null) {
            stringIntegerHashMap.put("露点", entries.get("dewPoint"));
        } else {
            stringIntegerHashMap.put("露点", "0.0");
        }
        if (entries.get("littleParticle") != null) {
            stringIntegerHashMap.put("尘埃粒子0.5", entries.get("littleParticle"));
        } else {
            stringIntegerHashMap.put("尘埃粒子0.5", "0.0");
        }
        if (entries.get("longParticle") != null) {
            stringIntegerHashMap.put("尘埃粒子5.0", entries.get("longParticle"));
        } else {
            stringIntegerHashMap.put("尘埃粒子5.0", "0.0");
        }
        return stringIntegerHashMap;
    }

    /**
     * NMP设备id集
     */
    static final List<String> NMP_SET = Lists.newArrayList("17");
    /**
     * 空调设备id集
     */
    static final List<String> AIR_CONDITION_SET = Lists.newArrayList("10", "11", "12");

    /**
     * 纯水设备id集
     */
    static final List<String> CLEAN_WATER_SET = Lists.newArrayList("14");

    /**
     * 除湿除尘设备id集
     */
    static final List<String> WET_DUST_SET = Lists.newArrayList("6", "8");

    /**
     * 空压设备id集
     */
    static final List<String> AIR_SET = Lists.newArrayList("7");
    /**
     * 冷源设备id集
     */
    static final List<String> COLD_SOURCE_SET = Lists.newArrayList("9");

    public Map<String, Object> getEquimentAlarm(){

        List<Alarm> alarms = baseMapper.getEquimentAlarm();
        Map<String, Object> result = new HashMap<>();
        List<Alarm> nmpAlarms = alarms.stream().filter(e -> NMP_SET.contains(e.getTypes())).collect(Collectors.toList());
        result.put("NMP设备", CollectionUtils.isEmpty(nmpAlarms) ? 0 : nmpAlarms.size());
        List<Alarm> airConditionAlarms = alarms.stream().filter(e -> AIR_CONDITION_SET.contains(e.getTypes())).collect(Collectors.toList());
        result.put("空调设备", CollectionUtils.isEmpty(airConditionAlarms) ? 0 : airConditionAlarms.size());
        List<Alarm> cleanWaterAlarms = alarms.stream().filter(e -> CLEAN_WATER_SET.contains(e.getTypes())).collect(Collectors.toList());
        result.put("纯水设备", CollectionUtils.isEmpty(cleanWaterAlarms) ? 0 : cleanWaterAlarms.size());
        List<Alarm> WetDustAlarms = alarms.stream().filter(e -> WET_DUST_SET.contains(e.getTypes())).collect(Collectors.toList());
        result.put("除湿除尘设备", CollectionUtils.isEmpty(WetDustAlarms) ? 0 : WetDustAlarms.size());
        List<Alarm> airSetAlarms = alarms.stream().filter(e -> AIR_SET.contains(e.getTypes())).collect(Collectors.toList());
        result.put("空压设备", CollectionUtils.isEmpty(airSetAlarms) ? 0 : airSetAlarms.size());
        List<Alarm> coldSourceAlarms = alarms.stream().filter(e -> COLD_SOURCE_SET.contains(e.getTypes())).collect(Collectors.toList());
        result.put("冷源设备", CollectionUtils.isEmpty(coldSourceAlarms) ? 0 : coldSourceAlarms.size());
        return result;
    }
}
